import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Modal, Form, DatePicker, InputNumber, message } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';

const { Option } = Select;
const { RangePicker } = DatePicker;

const MChooseNCardManagement = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('create'); // 'create' or 'edit'
  const [selectedCard, setSelectedCard] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const { userInfo } = useSelector((state) => state.auth);

  // 模拟的M选N权益卡数据
  const [mChooseNCards, setMChooseNCards] = useState([
    {
      id: '1',
      name: '3选1优惠套餐',
      totalOptions: 3,
      selectedOptions: 1,
      options: ['A套餐', 'B套餐', 'C套餐'],
      price: 199,
      startDate: '2024-01-01',
      endDate: '2024-03-31',
      usageCount: 123,
      maxSaleCount: 500,
      status: 'active',
      applicableTo: 'all',
      createdBy: 'admin',
    },
    {
      id: '2',
      name: '5选2会员专享',
      totalOptions: 5,
      selectedOptions: 2,
      options: ['X服务', 'Y服务', 'Z服务', 'A服务', 'B服务'],
      price: 299,
      startDate: '2024-01-10',
      endDate: '2024-06-30',
      usageCount: 89,
      maxSaleCount: 300,
      status: 'active',
      applicableTo: 'members',
      createdBy: 'admin',
    },
    {
      id: '3',
      name: '6选3春季大促',
      totalOptions: 6,
      selectedOptions: 3,
      options: ['春季套餐1', '春季套餐2', '春季套餐3', '春季套餐4', '春季套餐5', '春季套餐6'],
      price: 399,
      startDate: '2024-02-01',
      endDate: '2024-04-30',
      usageCount: 0,
      maxSaleCount: 400,
      status: 'upcoming',
      applicableTo: 'all',
      createdBy: 'admin',
    },
    {
      id: '4',
      name: '4选2冬季特惠',
      totalOptions: 4,
      selectedOptions: 2,
      options: ['冬季套餐A', '冬季套餐B', '冬季套餐C', '冬季套餐D'],
      price: 249,
      startDate: '2023-11-01',
      endDate: '2024-01-15',
      usageCount: 156,
      maxSaleCount: 350,
      status: 'expired',
      applicableTo: 'all',
      createdBy: 'admin',
    },
  ]);

  // 表格列定义
  const columns = [
    {
      title: '权益卡名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: '选择规则',
      key: 'rule',
      render: (record) => `从${record.totalOptions}个选项中选择${record.selectedOptions}个`,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (value) => `¥${value}`,
    },
    {
      title: '有效期',
      key: 'period',
      render: (record) => `${record.startDate} - ${record.endDate}`,
    },
    {
      title: '已使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'active':
            color = 'green';
            text = '活跃';
            break;
          case 'upcoming':
            color = 'orange';
            text = '即将开始';
            break;
          case 'expired':
            color = 'default';
            text = '已过期';
            break;
          default:
            color = 'default';
            text = '未知';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          {record.status !== 'expired' && (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{ marginRight: 8 }}
            >
              编辑
            </Button>
          )}
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </>
      ),
      width: 120,
    },
  ];

  // 过滤M选N权益卡数据
  const filteredCards = mChooseNCards.filter((card) => {
    const matchesSearch = card.name.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || card.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  // 打开创建模态框
  const showCreateModal = () => {
    form.resetFields();
    setModalType('create');
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (card) => {
    setSelectedCard(card);
    setModalType('edit');
    form.setFieldsValue({
      ...card,
      dateRange: [
        new Date(card.startDate),
        new Date(card.endDate),
      ],
      options: card.options.join('\n'),
    });
    setIsModalVisible(true);
  };

  // 删除M选N权益卡
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个M选N权益卡吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setMChooseNCards(mChooseNCards.filter((card) => card.id !== id));
        message.success('M选N权益卡已删除');
      },
    });
  };

  // 提交表单
  const handleSubmit = (values) => {
    // 处理选项文本，分割成数组
    const optionsArray = values.options.split('\n').filter(opt => opt.trim());
    
    if (modalType === 'create') {
      // 创建新M选N权益卡
      const newCard = {
        id: Date.now().toString(),
        ...values,
        options: optionsArray,
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
        usageCount: 0,
        status: 'active',
        createdBy: userInfo?.username,
      };
      setMChooseNCards([newCard, ...mChooseNCards]);
      message.success('M选N权益卡创建成功');
    } else {
      // 编辑M选N权益卡
      const updatedCards = mChooseNCards.map((card) =>
        card.id === selectedCard.id
          ? {
              ...card,
              ...values,
              options: optionsArray,
              startDate: values.dateRange[0].format('YYYY-MM-DD'),
              endDate: values.dateRange[1].format('YYYY-MM-DD'),
            }
          : card
      );
      setMChooseNCards(updatedCards);
      message.success('M选N权益卡更新成功');
    }
    setIsModalVisible(false);
  };

  // 刷新数据
  const handleRefresh = () => {
    // 这里应该调用API刷新数据，这里简化处理
    message.success('数据已刷新');
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>M选N权益卡管理</h2>
        <p style={{ color: '#8c8c8c' }}>管理和创建系统中的M选N权益卡</p>
      </div>

      <Card
        bordered={false}
        style={{ borderRadius: 8, marginBottom: 24 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 200 }}>
              <Input
                placeholder="搜索权益卡名称"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ borderRadius: 4 }}
              />
            </div>
            <Select
              placeholder="选择状态"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
              prefix={<FilterOutlined />}
            >
              <Option value="all">全部</Option>
              <Option value="active">活跃</Option>
              <Option value="upcoming">即将开始</Option>
              <Option value="expired">已过期</Option>
            </Select>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            创建M选N权益卡
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={filteredCards}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowKey="id"
        />
      </Card>

      {/* 创建/编辑M选N权益卡模态框 */}
      <Modal
        title={modalType === 'create' ? '创建M选N权益卡' : '编辑M选N权益卡'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          style={{ maxHeight: '60vh', overflowY: 'auto' }}
        >
          <Form.Item
            name="name"
            label="权益卡名称"
            rules={[{ required: true, message: '请输入权益卡名称' }]}
          >
            <Input placeholder="请输入权益卡名称" />
          </Form.Item>

          <Form.Item
            name="totalOptions"
            label="总选项数(M)"
            rules={[{ required: true, message: '请输入总选项数' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="selectedOptions"
            label="可选择数量(N)"
            rules={[{ required: true, message: '请输入可选择数量' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="options"
            label="选项内容（每行一个选项）"
            rules={[{ required: true, message: '请输入选项内容' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入选项内容，每行一个选项" />
          </Form.Item>

          <Form.Item
            name="price"
            label="销售价格"
            rules={[{ required: true, message: '请输入销售价格' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="maxSaleCount"
            label="最大销售数量"
            rules={[{ required: true, message: '请输入最大销售数量' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="dateRange"
            label="有效期"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="applicableTo"
            label="适用对象"
            rules={[{ required: true, message: '请选择适用对象' }]}
          >
            <Select placeholder="请选择适用对象">
              <Option value="all">所有用户</Option>
              <Option value="new_users">新用户</Option>
              <Option value="members">会员用户</Option>
              <Option value="vip">VIP用户</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Button style={{ marginRight: 8 }} onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {modalType === 'create' ? '创建' : '保存'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MChooseNCardManagement;